package com.ssm.sport.common;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * SQL执行日志辅助类
 * 通过AOP捕获Mapper方法的调用并记录日志
 */
@Aspect
@Component
@Slf4j
public class SqlLogHelper {

    /**
     * 拦截所有Mapper接口的方法调用
     */
    @Around("execution(* com.ssm.sport.mapper.*Mapper.*(..))")
    public Object logSqlExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String mapperName = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        
        StringBuilder argInfo = new StringBuilder();
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                if (arg != null) {
                    argInfo.append(arg.toString()).append(", ");
                } else {
                    argInfo.append("null, ");
                }
            }
            if (argInfo.length() > 2) {
                argInfo.delete(argInfo.length() - 2, argInfo.length());
            }
        }
        
        log.debug("SQL执行开始: {}#{}, 参数: [{}]", mapperName, methodName, argInfo);
        long startTime = System.currentTimeMillis();
        
        try {
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            log.debug("SQL执行成功: {}#{}, 耗时: {}ms, 参数: [{}]", 
                    mapperName, methodName, (endTime - startTime), argInfo);
            return result;
        } catch (Throwable e) {
            long endTime = System.currentTimeMillis();
            log.error("SQL执行异常: {}#{}, 耗时: {}ms, 参数: [{}], 异常: {}", 
                    mapperName, methodName, (endTime - startTime), argInfo, e.getMessage(), e);
            throw e;
        }
    }
} 